package timing.ukulele.third.msgChannel.handle.impl;

import com.alibaba.fastjson2.JSON;
import com.alibaba.fastjson2.JSONObject;
import com.aliyuncs.CommonRequest;
import com.aliyuncs.CommonResponse;
import com.aliyuncs.DefaultAcsClient;
import com.aliyuncs.IAcsClient;
import com.aliyuncs.exceptions.ClientException;
import com.aliyuncs.http.MethodType;
import com.aliyuncs.profile.DefaultProfile;
import com.google.common.base.Throwables;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import timing.ukulele.third.dictionary.msg.MsgChannelType;
import timing.ukulele.third.msgChannel.handle.BaseHandler;
import timing.ukulele.third.msgChannel.model.RecallTaskInfo;
import timing.ukulele.third.msgChannel.model.SendTaskInfo;
import timing.ukulele.third.msgChannel.model.account.sms.ALYSmsAccount;
import timing.ukulele.third.msgChannel.model.content.CommonContentParamModel;
import timing.ukulele.third.msgChannel.model.content.SmsContentModel;
import timing.ukulele.third.msgChannel.param.HandleMessageBaseResponse;
import timing.ukulele.third.msgChannel.utils.AccountUtils;
import java.util.List;
import java.util.stream.Collectors;

/**
 * 阿里云短信推送服务
 * https://help.aliyun.com/zh/sms/getting-started/use-sms-api?spm=a2c4g.11186623.help-menu-44282.d_2_2.299e6433xWEi8T
 * @author zh
 */
@Component
@Slf4j
public class ALYSmsHandler extends BaseHandler {

    @Autowired
    private AccountUtils accountUtils;

    public ALYSmsHandler() {
        channelCode = MsgChannelType.ALYSms.getCode();
    }

    @Override
    public HandleMessageBaseResponse send(SendTaskInfo sendTaskInfo) {
        // 构造返回值
        HandleMessageBaseResponse result = new HandleMessageBaseResponse();
        // 获取账号信息
        SmsContentModel smsContentModel = (SmsContentModel) sendTaskInfo.getContentModel();
        ALYSmsAccount alySmsAccount = accountUtils.getAccountById(
                sendTaskInfo.getSendAccountId(), ALYSmsAccount.class);
        // 构造IAcsClient
        DefaultProfile profile = DefaultProfile.getProfile(alySmsAccount.getRegionId(), alySmsAccount.getAccessKeyId(), alySmsAccount.getSecret());
        IAcsClient client = new DefaultAcsClient(profile);
        // 请求阿里云进行短信发送
        CommonRequest request = new CommonRequest();
        request.setSysMethod(MethodType.POST);
        request.setSysDomain(alySmsAccount.getUrl());
        request.setSysVersion(alySmsAccount.getSysVersion());
        request.putQueryParameter("RegionId", alySmsAccount.getRegionId());
        request.setSysAction("SendSms");
        // 多个接收者用逗号相隔
        request.putQueryParameter("PhoneNumbers", String.join(",", sendTaskInfo.getReceiver()));
        request.putQueryParameter("SignName", alySmsAccount.getSignName());
        request.putQueryParameter("TemplateCode", smsContentModel.getTemplateId());
        request.putQueryParameter("TemplateParam", buildTemplateParam(smsContentModel));
        try {
            // 处理返回值
            CommonResponse response = client.getCommonResponse(request);
            log.info("OfficialAccountHandler#send response:{},params:{}", response.getData(), JSON.toJSONString(sendTaskInfo));
            JSONObject responseJson = JSONObject.parseObject(response.getData());
            if(responseJson.getString("Code").equals("OK")) {
                result.setHandleFlag(true);
            }else{
                result.setHandleFlag(false);
            }
            result.setHandleMessage(responseJson.getString("Message"));
        } catch (ClientException e) {
            log.error("OfficialAccountHandler#send fail:{},params:{}", Throwables.getStackTraceAsString(e), JSON.toJSONString(sendTaskInfo));
            result.setHandleFlag(true);
        }
        return result;
    }

    private String buildTemplateParam(SmsContentModel smsContentModel) {
        String paramListJson = smsContentModel.getParamList();
        // 将json字符串转为对象集合
        List<CommonContentParamModel> paramModelList = JSON.parseArray(paramListJson, CommonContentParamModel.class);
        // 转为阿里云所需要模板参数格式->json对象格式
        return JSON.toJSONString(paramModelList.stream()
                .collect(Collectors.toMap(CommonContentParamModel::getKey, CommonContentParamModel::getValueData)));
    }

    /**
     * 阿里云
     * https://developers.weixin.qq.com/doc/offiaccount/Subscription_Messages/api.html
     * @param recallTaskInfo
     */
    @Override
    public HandleMessageBaseResponse recall(RecallTaskInfo recallTaskInfo) {
        return HandleMessageBaseResponse.builder().handleFlag(true).build();
    }

}

